/* ForEachConverter.java

	Purpose:
		
	Description:
		
	History:
		10:45:00 AM Jan 27, 2015, Created by jameschu

Copyright (C) 2015 Potix Corporation. All Rights Reserved.
*/
package org.zkoss.zuti.zul;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.zkoss.util.Maps;
import org.zkoss.zul.ListModelArray;

/**
 * convert items in ForEach to ArrayList
 * @author jameschu
 * @since 8.0.0
 */
public class ForEachConverter implements Serializable {
	private static final long serialVersionUID = 20150127110000L;

	public Object coerceToUi(Object val) {
		if (val == null || val instanceof List) {
			return val;
		}
		Collection<Object> data = null;
		if (val instanceof Collection) {
			data = new ArrayList<Object>(((Collection<?>) val).size());
			data.addAll((Collection<?>) val);
		} else if (val instanceof Map) {
			data = new ArrayList<Object>(Maps.transferToSerializableEntrySet(((Map<?, ?>) val).entrySet()));
		} else if (val instanceof ListModelArray<?>) {
			data = Arrays.asList(((ListModelArray<?>) val).getInnerArray());
		} else if (val instanceof Object[]) {
			data = Arrays.asList((Object[]) val);
		} else if ((val instanceof Class) && Enum.class.isAssignableFrom((Class) val)) {
			data = Arrays.asList(((Class) val).getEnumConstants());
		}
		return data;
	}
}
